package com.liuyi.netty.im.commons.codes;

import com.liuyi.netty.im.commons.codes.serialize.ContentTypeSerializeManage;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @author Mr.Fmy
 * @since 2021-11-23
 */
@Slf4j
public class LimCodeEncode extends MessageToMessageEncoder<LimProtocol> {

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, LimProtocol message, List<Object> out) throws Exception {
        ByteBuf response = Unpooled.buffer();
        response.writeInt(message.getMagicNumber());
        response.writeByte(message.getVersion());
        response.writeByte(message.getDataType());
        response.writeByte(message.getCommand().getCommand());
        if (message.getData() != null) {
            byte[] data = ContentTypeSerializeManage.get(message.getDataType()).serialization(message.getData());
            response.writeInt(data.length);
            response.writeBytes(data);
        } else {
            response.writeInt(0);
        }
        out.add(response);
    }
}
